package xyz.zchao.blog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.zchao.blog.annotation.IgnoreToken;
import xyz.zchao.blog.pojo.Diary;
import xyz.zchao.blog.service.DiaryService;
import xyz.zchao.blog.util.PageResultVO;
import xyz.zchao.blog.util.ResultCode;
import xyz.zchao.blog.util.ResultVO;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Description: 日记控制器
 * @Author: guozongchao
 * @Date: 2020/5/7 16:20
 */
@RestController
@RequestMapping("/diary")
public class DiaryController {

    @Autowired
    private DiaryService diaryService;

    /**
     * 添加日记
     * @param record
     * @param request
     * @return
     */
    @PostMapping("/add")
    public ResultVO<String> addDiary(@RequestBody Diary record, HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        record.setUserId(userId);
        System.out.println(record.getContent());
        if(diaryService.create(record)>0){
            return new ResultVO<String>(ResultCode.SUCCESS,"添加成功");
        }
        return new ResultVO<String>(ResultCode.FAILED,"添加失败");
    }

    @PostMapping("/update")
    public ResultVO<?> updateDiary(@RequestBody Diary record) {
        if (diaryService.update(record)>0) {
            return new ResultVO<String>(ResultCode.SUCCESS,null);
        }
        return new ResultVO<List<Diary>>(ResultCode.FAILED, null);
    }

    @DeleteMapping("/{id}")
    public ResultVO<?> updateDiary(@PathVariable("id") int id) {
        if (diaryService.deleteById(id)>0) {
            return new ResultVO<String>(ResultCode.SUCCESS,null);
        }
        return new ResultVO<List<Diary>>(ResultCode.FAILED, null);
    }

    @IgnoreToken
    @GetMapping("/list")
    public ResultVO<?> getDiaryList(@RequestParam(required = false) Integer page,@RequestParam(required = false) Integer limit) {
        List<Diary> diaries = diaryService.retrieveAllByPaging(page, limit);
        long count = diaryService.getCount();
        return new PageResultVO<List<Diary>>(ResultCode.SUCCESS, diaries, count);
    }

}
